//
//  SYDPickUpThePassengersController.m
//  PinGJByOwnerSide
//
//  Created by lantaiyuan on 2017/8/17.
//  Copyright © 2017年 lantaiyuan. All rights reserved.
//

#import "SYDPickUpThePassengersController.h"
#import "SYDStationModel.h"
#import "SYDEndTheTripView.h"
#import "NaviPointAnnotation.h"
#import "SYDCusAnnotationView.h"
#import "SYDCalloutView.h"
#import "YMUserPointAnnotation.h"
@interface SYDPickUpThePassengersController ()<MAMapViewDelegate,UIGestureRecognizerDelegate, AMapSearchDelegate>
{
    CLLocationCoordinate2D coords1[1];
}

//高德地图
@property (nonatomic, strong) MAMapView *mapView;

///支持动画效果的点标注
@property (nonatomic, strong) YMUserPointAnnotation* annotation;

@property (nonatomic, strong) SYDCalloutView *calloutMapAnnotation;
@property(nonatomic,assign)BOOL showMakerInfo;
//站点
@property (nonatomic, assign) CGFloat mapCenterLon;//地图中心点经度
@property (nonatomic, assign) CGFloat mapCenterLat;//地图中心点纬度
@property (nonatomic, strong) NSMutableArray *mapStationList;//地图站点数组
@property(nonatomic,strong)NSMutableArray *stations;//站点数组
@property(nonatomic,strong)UIButton *startTripBtn;//开始行程
@property(nonatomic,strong)UIButton *endTripBtn;//结束行程

@property (nonatomic, strong) UIView *maskView;//遮罩View
@property (nonatomic, strong) SYDEndTheTripView *endTheTripView;
@property (nonatomic, strong) NSMutableArray *pointArr;//定位信息数组
//画线
@property (nonatomic, strong) MAPolyline *routeLine;
@property (nonatomic, strong) MAUserLocation *currentUL;//当前位置
@property(nonatomic,strong)NSString *matchId;

@property(nonatomic, strong) AMapSearchAPI *search;
@end

@implementation SYDPickUpThePassengersController
#pragma mark - 导航栏
- (void)navigationBarHandle{
    
    WEAKSELF
    [weakSelf backButtonAction:^{
        [weakSelf.navigationController popViewControllerAnimated:YES];
        
    }];
    
    [weakSelf rightNavButtonWithImage:[UIImage imageNamed:@"nav_button_call"] action:^{
        [SVProgressHUD displayInfoWithStatus:@"打电话"];
    }];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    //初始化地图
    [self initMapView];
    //获取行程详情
    [self getMyTrailDetailMessage];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationBar.title  = @"去接乘客";
    [self navigationBarHandle];
    
    self.matchId = self.sendsingleModel.matchId == nil?@"694df7b7818411e7ac0f00e066d54d33":self.sendsingleModel.matchId;
    
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
}
-(void)initBottonView{
    self.startTripBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 48, SCREEN_WIDTH, 48)];
    [self.view addSubview:self.startTripBtn];
    [self.startTripBtn setTitle:@"开始行程" forState:UIControlStateNormal];
    self.startTripBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.startTripBtn setTitleColor:WHITE_COLOR forState:UIControlStateNormal];
    self.startTripBtn.backgroundColor = GREEN_COLOR;
    self.startTripBtn.eventTimeInterval = 2.5;
    WEAKSELF
    [[self.startTripBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf startJourney];
    }];
    
    // 点击遮罩层
    [self.maskView jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        [weakSelf removeMaskOrPopup];
    }];
    self.endTheTripView.cancelBlock = ^{
        [weakSelf removeMaskOrPopup];
    };
    self.endTheTripView.sureBlock = ^{
        [weakSelf removeMaskOrPopup];
        [weakSelf.navigationController popViewControllerAnimated:YES];
    };
}

#pragma mark---获取行程轨迹
-(void)getMyTrailDetailMessage{
    
    NSDictionary *dict = [NSString resourcePathWithFileName:@"CarpoolDynamics.json"];
    TravelDetailModel *model = [TravelDetailModel mj_objectWithKeyValues:dict[@"obj"]];
    
    [self addStationAnnotationsAndPolylinesWith:model];
    
    //     WEAKSELF
    //    [[SYDNetwork shareTool]getMyTrailDetailWithOrderNo:self.regularRouteOrderNo success:^(NSURLSessionDataTask *task, id responseObject) {
    //       @try {
    //           if ([responseObject[@"statusCode"]integerValue] == 200) {
    //               if ([responseObject[@"obj"]isKindOfClass:[NSDictionary class]]) {
    //                   TravelDetailModel *model = [TravelDetailModel mj_objectWithKeyValues:responseObject[@"obj"]];
    //
    //                   self.firstStationName = model.firstStationName;
    //                   self.lastStationName = model.lastStationName;
    //                   self.totalDistance = model.totalDistance;
    //                   self.totalTimeConsuming = model.totalTimeConsuming;
    //                   self.totalIncome = model.totalIncome;
    //                   self.totalCount = model.totalCount;
    //                   //添加标注
    //                   [weakSelf addStationAnnotationsAndPolylinesWith:model];
    //                   [weakSelf addBottonView];
    //               }
    //           }else{
    //               [SVProgressHUD displayInfoWithStatus:responseObject[@"msg"]];
    //           }
    //       } @catch (NSException *exception) {
    //           NSLog(@"%@",exception.description);
    //       } @finally {
    //
    //       }
    //   } failure:^(NSURLSessionDataTask *task, NSError *error) {
    //       NSLog(@"%@",error);
    //   }];
}
#pragma mark---确定结束行程
-(void)confirmEndingJourney{
  [[SYDNetwork shareTool] confirmEndingJourneySuccess:^(NSURLSessionDataTask *task, id responseObject) {
      @try {
          if ([responseObject[@"statusCode"]integerValue] == 200) {
              NSLog(@"responseObject:%@",responseObject);
          }
      } @catch (NSException *exception) {
          NSLog(@"%@",exception.description);
      } @finally {
          
      }
  } failure:^(NSURLSessionDataTask *task, NSError *error) {
      NSLog(@"error:%@",error);
  }];
}
#pragma mark---开始行程
-(void)startJourney{
    WEAKSELF
    [[SYDNetwork shareTool] startJourneyWithCityCode:[YMSaveTool valueForKey:CityCode] lat:[YMSaveTool valueForKey:USER_LATITUDE] lon:[YMSaveTool valueForKey:USER_LONGITUDE] orderNo:self.matchId userId:[YMSaveTool valueForKey:USER_ID] success:^(NSURLSessionDataTask *task, id responseObject) {
        @try {
            if ([responseObject[@"statusCode"]integerValue] == 200) {
                NSLog(@"---responseObject:%@",responseObject);
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    self.endTripBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 48, SCREEN_WIDTH, 48)];
                    self.endTripBtn.eventTimeInterval = 2.0;
                    [self.endTripBtn setTitle:@"结束行程" forState:UIControlStateNormal];
                    self.endTripBtn.titleLabel.font = [UIFont systemFontOfSize:15];
                    [self.endTripBtn setTitleColor:WHITE_COLOR forState:UIControlStateNormal];
                    self.endTripBtn.backgroundColor = GREEN_COLOR;
                    [UIView animateWithDuration:0.1 animations:^{
                        [weakSelf.startTripBtn removeFromSuperview];
                        [weakSelf.view addSubview:weakSelf.endTripBtn];
                    }];
                });
            } else {
                [SVProgressHUD displayInfoWithStatus:responseObject[@"msg"]];
            }
        } @catch (NSException *exception) {
            NSLog(@"%@",exception.description);
        } @finally {
            
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
    }];
    //结束行程操作
    [[weakSelf.endTripBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf endJourney];
    }];
}
#pragma mark---结束行程
-(void)endJourney{
    WEAKSELF
    [[SYDNetwork shareTool] endJourneyWithCityCode:[YMSaveTool valueForKey:CityCode] lat:[YMSaveTool valueForKey:USER_LATITUDE] lon:[YMSaveTool valueForKey:USER_LONGITUDE] orderNo:self.matchId userId:[YMSaveTool valueForKey:USER_ID] success:^(NSURLSessionDataTask *task, id responseObject) {
      @try {
          if ([responseObject[@"statusCode"]integerValue] == 200) {
              NSLog(@"---responseObject:%@",responseObject);
              [weakSelf.view addSubview:weakSelf.maskView];
              [weakSelf.view addSubview:weakSelf.endTheTripView];
          } else {
              [SVProgressHUD displayInfoWithStatus:responseObject[@"msg"]];
          }
      } @catch (NSException *exception) {
          NSLog(@"%@",exception.description);
      } @finally {
          
      }
  } failure:^(NSURLSessionDataTask *task, NSError *error) {
      NSLog(@"error:%@",error);
  }];
}
// 移除遮罩层和弹窗
- (void)removeMaskOrPopup{
    
    [self.endTheTripView removeFromSuperview];
    
    [self.maskView removeFromSuperview];
    
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}
#pragma mark - 高德地图初始化
- (void)initMapView{
    //1.判断key是否存在
    if ([MAMAP_KEY length] == 0) {
        NSString *reson = [NSString stringWithFormat:@"apikey为空,请检查key设置时候正确"];
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:reson preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:cancel];
        [alert presentViewController:self animated:NO completion:nil];
    }
    [YMMaMapServices start];
    
    if (self.mapView.userTrackingMode != MAUserTrackingModeFollow) {
        self.mapView.userTrackingMode = MAUserTrackingModeNone;
        [self.mapView setZoomLevel:14 animated:YES];
    }
    [self.view addSubview:self.mapView];
    [self initBottonView];
}

#pragma mark---轨迹和站点标注数据
-(void)addStationAnnotationsAndPolylinesWith:(TravelDetailModel *)model{
    NSArray *Polylines = [model.trailDetail componentsSeparatedByString:@","];
    WEAKSELF
    [Polylines enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        NSArray *coord = [obj componentsSeparatedByString:@"|"];
        coordModel *coordM = [[coordModel alloc]init];
        coordM.latitude = coord[1];
        coordM.longitude = coord[0];
        [weakSelf.pointArr addObject:coordM];
    }];
    CGFloat locationLat;
    CGFloat locationLong;
    if (weakSelf.pointArr.count % 2 == 0) {
        coordModel *coordM = weakSelf.pointArr[weakSelf.pointArr.count / 2];
        locationLat = [coordM.latitude floatValue];
        locationLong = [coordM.longitude floatValue];
    }else{
        //NSLog(@"--%@",weakSelf.pointArr[(weakSelf.pointArr.count -1) / 2]);
        coordModel *coordM = weakSelf.pointArr[(weakSelf.pointArr.count -1) / 2];
        locationLat = [coordM.latitude floatValue];
        locationLong = [coordM.longitude floatValue];
    }
    
    CLLocationCoordinate2D centerCoordinate = CLLocationCoordinate2DMake(locationLat,locationLong);
    [self.mapView setCenterCoordinate:centerCoordinate];
    
    coordModel *coordFirst = weakSelf.pointArr[0];
    coordModel *coordLast = weakSelf.pointArr.lastObject;
    NaviPointAnnotation *startAnnotation = [[NaviPointAnnotation alloc]init];
    startAnnotation.navPointType = NaviPointAnnotationStart;
    startAnnotation.coordinate = CLLocationCoordinate2DMake([coordFirst.latitude floatValue], [coordFirst.longitude floatValue]);;
    startAnnotation.title = model.firstStationName;
    [self.mapView addAnnotation:startAnnotation];
    
    
    NaviPointAnnotation *endAnnotation = [[NaviPointAnnotation alloc]init];
    endAnnotation.navPointType = NaviPointAnnotationEnd;
    endAnnotation.coordinate = CLLocationCoordinate2DMake([coordLast.latitude floatValue], [coordLast.longitude floatValue]);
    endAnnotation.title = model.lastStationName;
    [self.mapView addAnnotation:endAnnotation];
    
    if (self.mapStationList.count > 0) {
        [self.mapStationList removeAllObjects];
    }
    //添加站点
    self.mapStationList = [carpoolRouteStationModel mj_objectArrayWithKeyValuesArray:model.carpoolRouteStations];
    [self addPointAnnotations:self.mapStationList];
    
    //add overlay=------画轨迹
    [self initCoordinates];
}
/**添加地图标注--站点*/
- (void)addPointAnnotations:(NSArray *)points{
    
    if (self.stations.count > 0) {
        [self.stations removeAllObjects];
        [self.mapView removeAnnotations:self.stations];
    }
    
    NSMutableArray * coors = [NSMutableArray array];
    [points enumerateObjectsUsingBlock:^(carpoolRouteStationModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        YMUserPointAnnotation *pointAnnotation = [[YMUserPointAnnotation alloc]init];
        pointAnnotation.coordinate = CLLocationCoordinate2DMake([obj.stationLat floatValue], [obj.stationLon floatValue]);
        pointAnnotation.timeStr = obj.arriveTime;
        pointAnnotation.locationStr = obj.stationName;
        if (![obj.upNum isEqualToString:@""]&&![obj.downNum isEqualToString:@""]) {
            pointAnnotation.numberStr = [NSString stringWithFormat:@"上车%@人,下车%@人",obj.upNum,obj.downNum];
        }else if ([obj.upNum isEqualToString:@""]&&![obj.downNum isEqualToString:@""]){
            pointAnnotation.numberStr = [NSString stringWithFormat:@"下车%@人",obj.downNum];
        }else if (![obj.upNum isEqualToString:@""]&&[obj.downNum isEqualToString:@""]){
            pointAnnotation.numberStr = [NSString stringWithFormat:@"上车%@人",obj.upNum];
        }
        pointAnnotation.index = idx;
        pointAnnotation.pointType = DetailMapPointAnnotationStation;
        [coors addObject:pointAnnotation];
    }];
    
    [self.stations addObjectsFromArray:coors];
    [self.mapView addAnnotations:self.stations];
}
/**绘制路径*/
- (void)initCoordinates {
    
    CLLocationCoordinate2D coords[self.pointArr.count];
    
    for (int i = 0; i < self.pointArr.count; i++) {
        coordModel *coordM= self.pointArr[i];
        if (i==0) {
            coords1[0].latitude = [coordM.latitude doubleValue];
            coords1[0].longitude = [coordM.longitude doubleValue];
        }
        coords[i].latitude = [coordM.latitude doubleValue];
        coords[i].longitude = [coordM.longitude doubleValue];
        
    }
    MAPolyline *polyline1 = [MAPolyline polylineWithCoordinates:coords count:sizeof(coords) / sizeof(coords[0])];
    [self.mapView addOverlays:@[polyline1]];
    
}
#pragma mark - MAMapViewDelegate
// 刷新用户位置信息
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation{
    
}

- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id <MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[MAPolyline class]])
    {
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:(MAPolyline *)overlay];
        polylineRenderer.lineWidth    = 8.f;
        [polylineRenderer loadStrokeTextureImage:[UIImage imageNamed:@"arrowTexture"]];
        return polylineRenderer;
        
    }
    
    return nil;
}
/**
 * 根据anntation生成对应的View
 * @param mapView 地图View
 * @param annotation 指定的标注
 * @return 生成的标注View
 */
-(MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[NaviPointAnnotation class]])
    {
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        MAPinAnnotationView*annotationView = (MAPinAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        annotationView.animatesDrop = NO;
        annotationView.canShowCallout= YES; //设置气泡可以弹出，默认为NO
        annotationView.draggable = NO;
        
        NaviPointAnnotation *navAnnotation = (NaviPointAnnotation *)annotation;
        if (navAnnotation.navPointType == NaviPointAnnotationStart) {
            [annotationView setPinColor:MAPinAnnotationColorGreen];
            
            annotationView.image = [UIImage imageNamed:@"icon_map_start"];
            annotationView.frame = CGRectMake(0, 0, 24, 24);
        }else if (navAnnotation.navPointType == NaviPointAnnotationEnd){
            
            [annotationView setPinColor:MAPinAnnotationColorRed];
            annotationView.image = [UIImage imageNamed:@"icon_map_end"];
            annotationView.frame = CGRectMake(0, 0, 24, 24);
        }
        
        return annotationView;
    }else if ([annotation isKindOfClass:[YMUserPointAnnotation class]]){
        static NSString *userLocationStyleIndetifier = @"userLocationStyleIndetifier";
        YMUserPointAnnotation * pointAnnotation = (YMUserPointAnnotation *)annotation;
        SYDCusAnnotationView * annotationView = (SYDCusAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:userLocationStyleIndetifier];
        if (annotationView == nil) {
            annotationView = [[SYDCusAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:userLocationStyleIndetifier];
        }
        if (pointAnnotation.pointType == DetailMapPointAnnotationStation) {
            annotationView.showBottomTitle = _showMakerInfo;
            annotationView.markerImage = @"icon_map_pathway_site";
            annotationView.markerSize = CGSizeMake(16, 16);
            annotationView.pointAnnotation = pointAnnotation;
            
            annotationView.enabled = NO;
        }
        return annotationView;
    
    }else if ([annotation isKindOfClass:[LTYPointAnnotation class]])
    {
        //站点
        LTYPointAnnotation * pointAnnotation = (LTYPointAnnotation *)annotation;
        static NSString *pointReuseIndentifier = @"stationPointReuseIndentifier";
        SYDCusAnnotationView * annotationView = (SYDCusAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil)
        {
            annotationView = [[SYDCusAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
            annotationView.calloutOffset = CGPointMake(0, -1);
        }
    
        annotationView.markerImage = @"icon_map_pathway_site";
        annotationView.locationStr = pointAnnotation.title;
        //annotationView.showBottomTitle = self.showMakerInfo;
        annotationView.enabled = NO;

        return annotationView;
    }else if ([annotation isKindOfClass:[MAPointAnnotation class]]){
      
    }
    return nil;
}
/**
 *  地图将要发生缩放时调用此接口
 *
 *  @param mapView       地图view
 *  @param wasUserAction 标识是否是用户动作
 */
- (void)mapView:(MAMapView *)mapView mapWillZoomByUser:(BOOL)wasUserAction{
    if (mapView.zoomLevel <14) {
        _showMakerInfo = NO;
        NSLog(@"地图变小了zoomLevel:%f",mapView.zoomLevel);
    }else{
        NSLog(@"标注正常显示zoomLevel:%f",mapView.zoomLevel);
        _showMakerInfo = YES;
    }
    
    [self goAwayAddPointAnnotations:self.mapStationList];
}
#pragma mark---重新添加标注
- (void)goAwayAddPointAnnotations:(NSArray *)points{
    
    [self.mapView removeAnnotations:self.stations];
    
    NSMutableArray * coors = [NSMutableArray array];
    [points enumerateObjectsUsingBlock:^(carpoolRouteStationModel * obj, NSUInteger idx, BOOL * _Nonnull stop) {
        YMUserPointAnnotation *pointAnnotation = [[YMUserPointAnnotation alloc]init];
        
        pointAnnotation.coordinate = CLLocationCoordinate2DMake([obj.stationLat floatValue], [obj.stationLon floatValue]);
        pointAnnotation.timeStr = obj.arriveTime;
        if (![obj.upNum isEqualToString:@""]&&![obj.downNum isEqualToString:@""]) {
            pointAnnotation.numberStr = [NSString stringWithFormat:@"上车%@人,下车%@人",obj.upNum,obj.downNum];
        }else if ([obj.upNum isEqualToString:@""]&&![obj.downNum isEqualToString:@""]){
            pointAnnotation.numberStr = [NSString stringWithFormat:@"下车%@人",obj.downNum];
        }else if (![obj.upNum isEqualToString:@""]&&[obj.downNum isEqualToString:@""]){
            pointAnnotation.numberStr = [NSString stringWithFormat:@"上车%@人",obj.upNum];
        }
        pointAnnotation.locationStr = obj.stationName;
        pointAnnotation.index = idx;
        pointAnnotation.pointType = DetailMapPointAnnotationStation;
        [coors addObject:pointAnnotation];
    }];
    
    if (coors.count > 0) {
        [self.stations removeAllObjects];
        [self.stations addObjectsFromArray:coors];
    }
    [self.mapView addAnnotations:self.stations];
}
//定位失败
- (void)mapView:(MAMapView *)mapView didFailToLocateUserWithError:(NSError *)error {
    NSString *errorString = @"";
    switch([error code]) {
        case kCLErrorDenied:
            //Access denied by user
            errorString = @"Access to Location Services denied by user";
            break;
        case kCLErrorLocationUnknown:
            //Probably temporary...
            errorString = @"Location data unavailable";
            //Do something else...
            break;
        default:
            errorString = @"An unknown error has occurred";
            break;
    }
}
#pragma mark---移除地图,销毁控制器
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self clearMapView];
}
#pragma mark - clear mapview
- (void)clearMapView {
    self.mapView.showsUserLocation = NO;
    
    [self.mapView removeAnnotations:self.mapView.annotations];
    
    [self.mapView removeOverlays:self.mapView.overlays];
    self.mapView.delegate = nil;
    [self.mapView removeFromSuperview];
    self.mapView = nil;
}
-(void)dealloc{
    printf(__PRETTY_FUNCTION__);
}
#pragma mark---Lazy
- (MAMapView *)mapView{
    if (!_mapView) {
        //地图初始化
        _mapView = [[MAMapView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
        _mapView.compassOrigin = CGPointMake(_mapView.compassOrigin.x, kDefaultControlMargin);
        _mapView.scaleOrigin = CGPointMake(_mapView.scaleOrigin.x, kDefaultControlMargin);
        //改变地图Logo”、“指南针”和“比例尺”三种地图控件
        _mapView.logoCenter = CGPointMake(1000, 450);
        _mapView.logoCenter = CGPointMake(CGRectGetWidth(self.view.bounds)-55, 450);
        //self.mapView.showsLabels = NO;
        _mapView.showsCompass = NO;//不显示指南针
        _mapView.showsScale = NO;//不显示比例尺
        
        _mapView.delegate = self;
        _mapView.showsUserLocation = NO;
        _mapView.rotateEnabled = NO;
        _mapView.showsIndoorMap = YES;
        _mapView.rotateCameraEnabled= NO;    //NO表示禁用倾斜手势，YES表示开启
        _mapView.customizeUserLocationAccuracyCircleRepresentation = YES;
        _mapView.zoomLevel = 13;
    }
    return _mapView;
}

- (NSMutableArray *)mapStationList{
    if (!_mapStationList) {
        _mapStationList = [NSMutableArray array];
    }
    return _mapStationList;
}
-(NSMutableArray *)stations{
    if (!_stations) {
        _stations = [NSMutableArray array];
    }
    return _stations;
}
-(NSMutableArray *)pointArr{
    if (!_pointArr) {
        _pointArr = [NSMutableArray array];
    }
    return _pointArr;
}
- (UIView *)maskView{
    if (!_maskView) {
        _maskView = [[UIView alloc] initWithFrame:SCREEN_RECT];
        _maskView.backgroundColor = [UIColor blackColor];
        _maskView.alpha = 0.3;
    }
    return _maskView;
}
-(SYDEndTheTripView *)endTheTripView{
    if (!_endTheTripView) {
        _endTheTripView = [[SYDEndTheTripView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 266, SCREEN_WIDTH, 266)];
    }
    return _endTheTripView;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - AMapSearchDelegate

- (void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response{
    if (response.route == nil)
    {
        return;
    }
    
    NSLog(@"线路规划成功");
    //解析response获取路径信息，具体解析见 Demo
}

- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    NSLog(@"Error: %@", error);
}

@end

//#import "Tracking.h"
//
//@interface MainViewController ()<MAMapViewDelegate, TrackingDelegate>
//
//@property (nonatomic, strong) MAMapView *mapView;
//
//@property (nonatomic, strong) Tracking *tracking;
//
//@end
//
//@implementation MainViewController
//@synthesize mapView  = _mapView;
//@synthesize tracking = _tracking;
//
//#pragma mark - MAMapViewDelegate
//
//- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
//{
//    if (annotation == self.tracking.annotation)
//    {
//        static NSString *trackingReuseIndetifier = @"trackingReuseIndetifier";
//        
//        MAAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:trackingReuseIndetifier];
//        
//        if (annotationView == nil)
//        {
//            annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:trackingReuseIndetifier];
//        }
//        
//        annotationView.canShowCallout = NO;
//        annotationView.image = [UIImage imageNamed:@"ball"];
//        
//        return annotationView;
//    }
//    
//    return nil;
//}
//
//- (MAOverlayView *)mapView:(MAMapView *)mapView viewForOverlay:(id <MAOverlay>)overlay
//{
//    if (overlay == self.tracking.polyline)
//    {
//        MAPolylineView *polylineView = [[MAPolylineView alloc] initWithPolyline:overlay];
//        
//        polylineView.lineWidth   = 4.f;
//        polylineView.strokeColor = [UIColor redColor];
//        
//        return polylineView;
//    }
//    
//    return nil;
//}
//
//#pragma mark - TrackingDelegate
//
//- (void)willBeginTracking:(Tracking *)tracking
//{
//    NSLog(@"%s", __func__);
//}
//
//- (void)didEndTracking:(Tracking *)tracking
//{
//    NSLog(@"%s", __func__);
//}
//
//#pragma mark - Handle Action
//
//- (void)handleRunAction
//{
//    if (self.tracking == nil)
//    {
//        [self setupTracking];
//    }
//    
//    [self.tracking execute];
//}
//
//#pragma mark - Setup
//
///* 构建mapView. */
//- (void)setupMapView
//{
//    [MAMapServices sharedServices].apiKey = @"ed38fb973877e657b379bfce7840656d";
//    
//    self.mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];
//    self.mapView.delegate = self;
//    
//    [self.view addSubview:self.mapView];
//}
//
///* 构建轨迹回放. */
//- (void)setupTracking
//{
//    NSString *trackingFilePath = [[NSBundle mainBundle] pathForResource:@"GuGong" ofType:@"tracking"];
//    
//    NSData *trackingData = [NSData dataWithContentsOfFile:trackingFilePath];
//    
//    CLLocationCoordinate2D *coordinates = (CLLocationCoordinate2D *)malloc(trackingData.length);
//    
//    /* 提取轨迹原始数据. */
//    [trackingData getBytes:coordinates length:trackingData.length];
//    
//    /* 构建tracking. */
//    self.tracking = [[Tracking alloc] initWithCoordinates:coordinates count:trackingData.length / sizeof(CLLocationCoordinate2D)];
//    self.tracking.delegate = self;
//    self.tracking.mapView  = self.mapView;
//    self.tracking.duration = 5.f;
//    self.tracking.edgeInsets = UIEdgeInsetsMake(50, 50, 50, 50);
//}
//
//- (void)setupNavigationBar
//{
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Run"
//                                                                              style:UIBarButtonItemStyleBordered
//                                                                             target:self
//                                                                             action:@selector(handleRunAction)];
//}
//#pragma mark - Life Cycle
//
//- (instancetype)init
//{
//    if (self = [super init])
//    {
//        self.title = @"轨迹回放";
//    }
//    
//    return self;
//}
//
//- (void)viewDidLoad
//{
//    [super viewDidLoad];
//    
//    [self setupNavigationBar];
//    
//    [self setupMapView];
//}
//
//- (void)viewWillAppear:(BOOL)animated
//{
//    [super viewWillAppear:animated];
//    
//    self.navigationController.navigationBar.barStyle    = UIBarStyleBlack;
//    self.navigationController.navigationBar.translucent = NO;
//}
//
//- (void)viewWillLayoutSubviews
//{
//    [super viewWillLayoutSubviews];
//    
//    self.mapView.frame = self.view.bounds;
//}
//
//@end




